/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package fr.loof.fonzie;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.persistence.Id;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import fr.loof.fonzie.dialects.JPADialect;

/**
 * @author <a href="nicolas@apache.org">Nicolas De Loof</a>
 */
public class JPAUtils
{
    protected static Logger logger = LoggerFactory.getLogger( JPAUtils.class );

    /**
     * The active JPA implementation Dialect. Autodetected on class loading based on supported implementations. Maybe
     * overriden using {{@link #setJPADialect(JPADialect)}.
     */
    private static JPADialect dialect;
    static
    {
        for ( String className : JPADialect.SUPPORTED_DIALECTS )
        {
            try
            {
                dialect = (JPADialect) Class.forName( className ).newInstance();
                break;
            }
            catch ( Exception e )
            {
                //
            }
        }
    }

    /**
     * Configure a custom JPADialect, typically to use Fonzie with an unsupported JPA implementation (in such cas,
     * consider contribution please)
     */
    public static void setJPADialect( JPADialect dialect )
    {
        JPAUtils.dialect = dialect;
    }

    private JPAUtils()
    {
        super();
    }


    /**
     * Read the @Id attribute of an @Entity.
     */
    public static Object getId( Object entity )
    {
        @SuppressWarnings( "unused" )
        Class<?> targetClass = entity.getClass();
        Field f = getIdField( entity );
        return ReflectionUtils.getField( f, writeReplace( entity ) );
    }

    @SuppressWarnings( "unchecked" )
    private static final ConcurrentMap<Class, Field> ID_FIELDS = new ConcurrentHashMap<Class, Field>();

    /**
     * Detects the @Id attribute of an entity and return the {@link Field} object that can be used to access it.
     * <p>
     * Internally uses a ConcurrentMap for better performances.
     */
    public static Field getIdField( Object entity )
    {
        Class<?> targetClass = entity.getClass();
        Field f = ID_FIELDS.get( targetClass );
        if ( f == null )
        {
            f = getIdField( targetClass );
            logger.debug( "{} ID field is {}", targetClass, f );
            ID_FIELDS.putIfAbsent( targetClass, f );
        }
        return f;
    }

    /**
     * Extract (if necessary) the underlying object from a JPA proxy, so that it can be safelly used for type checking.
     * Be aware such un-proxied object is not managed anymore. Any data access / graph navigation NOT be under control
     * of the EntityManager and its data integrity / lazy-loading management.
     * <p>
     * Internally delegates to an JPA implementation specific component
     */
    protected static <T> T writeReplace( T entity )
    {
        return dialect.writeReplace( entity );
    }

    /**
     * Fiel @Id {@link Field} in the targetClass Hierarchy
     */
    private static Field getIdField( Class<?> targetClass )
    {
        do
        {
            for ( Field field : targetClass.getDeclaredFields() )
            {
                if ( field.getAnnotation( Id.class ) != null )
                {
                    ReflectionUtils.makeAccessible( field );
                    return field;
                }
            }
            targetClass = targetClass.getSuperclass();
        }
        while ( targetClass != null && targetClass != Object.class );
        throw new IllegalArgumentException( "Entity " + targetClass + " has no @Id field" );
    }
}
